import java.awt.Point;


public class PointLineDistance {
    
    
    public static Point ptClosestTo(int x1, int y1, int x2, int y2, Point p)
    {
        Point res = new Point(0, 0);
        ptClosestTo(x1, y1, x2, y2, p, res);
        return res;
    }

    public static void ptClosestTo(int x1, int y1, int x2, int y2, Point p, Point res)
    {
        if(y1 == y2 && x1 == x2)
        {
            res.x = x1;
            res.y = y1;
            return;
        }
        if(y1 == y2)
        {
            res.y = y1;
            res.x = mid(x1, x2, p.x);
            return;
        }
        if(x1 == x2)
        {
            res.x = x1;
            res.y = mid(y1, y2, p.y);
            return;
        }
        int dx = x2 - x1;
        int dy = y2 - y1;
        res.x = dy * (dy * x1 - dx * (y1 - p.y)) + dx * dx * p.x;
        res.x = res.x / (dx * dx + dy * dy);
        res.y = (dx * (p.x - res.x)) / dy + p.y;
        if(x2 > x1)
        {
            if(res.x > x2)
            {
                res.x = x2;
                res.y = y2;
            } else
            if(res.x < x1)
            {
                res.x = x1;
                res.y = y1;
            }
        } else
        if(res.x < x2)
        {
            res.x = x2;
            res.y = y2;
        } else
        if(res.x > x1)
        {
            res.x = x1;
            res.y = y1;
        }
    }
    
    private static int mid(int a, int b, int c)
    {
        if(a <= b)
        {
            if(b <= c)
                return b;
            if(c <= a)
                return a;
            else
                return c;
        }
        if(b >= c)
            return b;
        if(c >= a)
            return a;
        else
            return c;
    }

}
